<?php

namespace App\V3\V3_2_7\Controllers;

use App\V3\V3_2_7\Models\AdminAddendumModel;
use App\V3\V3_2_7\Services\UploadImgService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use OSS\Core\OssException;
use OSS\Http\RequestCore_Exception;
use OSS\OssClient;

class UploadController extends BaseController
{
    protected $ossClient;

    public function __construct(Request $request)
    {
        parent::__construct($request);

        $this->ossClient = new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint'),
        );
    }

    /**
     * 图片上传
     * @param Request $request
     * 2022/8/18 10:09
     * Author: Sun Wu
     * @return array|\Illuminate\Http\JsonResponse|string[]
     */
    public function upload(Request $request)
    {
        $files = $request->file('images');
        if (empty($files)) {
            return $this->fail('', '请选择图片');
        }

        $fileSize = $files->getSize();

        if ($fileSize > 2097152) {
            //return ['code' => 1, 'msg' => '图片大小不能超出2M', 'data' => ''];
            return $this->fail('', '图片大小不能超出2M');
        }

        if (!in_array($files->extension(), ['jpg', 'jpeg', 'png'])) {
            //return ['code' => '1', '不支持的图片格式，当前仅支持`png`和`jpg`以及`jpeg`', 'data' => ''];
            return $this->fail('', '不支持的图片格式，当前仅支持`png`和`jpg`以及`jpeg`');
        }

        $uploadPath = $files->store(date('Y') . '/' . date('m') . '/' . date('d'));

        $fullPath = '/uploads/' . $uploadPath;
        $ossPath = ltrim($fullPath, './');
        $path = public_path() . $fullPath;
        $result = saveFileSize(
            ['main_id' => $this->getMainUserId()],
            $fileSize,
            []
        );
        if ($result['code']) {
            //删除服务器上传后存储的图片
            unlink($path);

            return response()->json(
                $result
            );
        }
        $client = $this->ossClient;
        $imgData = [
            'img_path' => $fullPath,
            'main_id' => $this->getMainUserId(),
            'user_id' => $this->getUserId(),
            'created_at' => time()
        ];
        try {
            $client->uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
        } catch (OssException|RequestCore_Exception $e) {
            unlink($path);
            AdminAddendumModel::query()
                ->where('main_id', $this->getMainUserId())
                ->decrement('file_total_size', $fileSize);
            Log::debug('图片上传异常：' . var_export($e->getMessage(), true));
            return fail('', '上传失败');
        }
        //删除服务器上传后存储的图片
        unlink($path);
        UploadImgService::saveImg($imgData);
        return $this->success(config('app.aliyun_oss_bucket_url') . $fullPath);
    }
}
